package com.okhttp.comment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.baselibrary.BaseConstant;
import com.baselibrary.base.BaseData;
import com.baselibrary.manager.DialogManager;
import com.baselibrary.manager.LoadingManager;
import com.baselibrary.router.ActivityRouter;
import com.baselibrary.utils.ARouterUtils;
import com.baselibrary.utils.ScreenUtils;
import com.baselibrary.utils.SpUtils;
import com.like.LikeButton;
import com.okhttp.SendRequest;
import com.okhttp.callbacks.GenericsCallback;
import com.okhttp.sample_okhttp.JsonGenericsSerializator;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.HashMap;

import okhttp3.Call;

/**
 * @author 关忆北丶
 * @description:
 * @date :2021/3/29 11:54
 * 基类自定义View  处理业务
 */
public class BusinessLayout extends LinearLayout {


    protected Activity activity;
    public static CommentHelp mCommentHelp;
    protected OnEndingViewListener mOnEmptyViewListener;

    public BusinessLayout(Context context) {
        super(context);
        mCommentHelp = ActivityRouter.getARouterInterface(ActivityRouter.COMMENT.COMMENT_HELP);
    }

    public BusinessLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mCommentHelp = ActivityRouter.getARouterInterface(ActivityRouter.COMMENT.COMMENT_HELP);
    }

    public BusinessLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mCommentHelp = ActivityRouter.getARouterInterface(ActivityRouter.COMMENT.COMMENT_HELP);
    }

    public void setActivity(Activity activity) {
        this.activity = activity;
    }

    public void setEndingViewListener(OnEndingViewListener onEmptyViewListener) {
        this.mOnEmptyViewListener = onEmptyViewListener;
    }

    /**
     * 主评论点赞
     *
     * @param id                评论的Id
     * @param mIvCommentGive
     * @param mTvCommentGiveNum
     * @param listener
     */
    public void giveClick(int id, LikeButton mIvCommentGive, TextView mTvCommentGiveNum, CommentBean.DataBean.CommentInfoBean norMarListBean, OnGiveFinishListener listener) {
        String giveNum = mTvCommentGiveNum.getText().toString().trim();
        if (TextUtils.isEmpty(giveNum))
            return;

        if (!mIvCommentGive.isLiked()) {
            //取消点赞
            favoriteFun(activity, SpUtils.getInstance().getLoadUserBean().getData().getToken(), "1", String.valueOf(id), false, new OnGiveListener() {
                @Override
                public void onGiveSuccess() {
                    int giveI = Integer.parseInt(giveNum);
                    if (giveI > 0) {
                        giveI = giveI - 1;
                    } else {
                        giveI = 0;
                    }

                    if (listener != null) {
                        listener.onGiveFinish();
                        norMarListBean.setSupportNum(giveI);
                        norMarListBean.setSupported(CommentBean.FALSE);
                        mTvCommentGiveNum.setText(String.valueOf(norMarListBean.getSupportNum()));
                        mTvCommentGiveNum.setVisibility(norMarListBean.getSupportNum() == 0 ? GONE : VISIBLE);
                        //mIvCommentGive.setSelected(norMarListBean.isSupported() == CommentBean.TRUE);
                        mIvCommentGive.setLiked(norMarListBean.isSupported() == CommentBean.TRUE);
                    }
                }

                @Override
                public void onGiveFail() {
                    //ToastUtils.showShort(getContext(), "网络错误");
                }
            });
        } else {
            //点赞
            favoriteFun(activity, SpUtils.getInstance().getLoadUserBean().getData().getToken(), "1", String.valueOf(id), true, new OnGiveListener() {
                @Override
                public void onGiveSuccess() {
                    int giveI = Integer.parseInt(giveNum);
                    if (listener != null) {
                        listener.onGiveFinish();
                        norMarListBean.setSupportNum(giveI + 1);
                        norMarListBean.setSupported(CommentBean.TRUE);
                        mTvCommentGiveNum.setText(String.valueOf(norMarListBean.getSupportNum()));
                        mTvCommentGiveNum.setVisibility(norMarListBean.getSupportNum() == 0 ? GONE : VISIBLE);
                        //mIvCommentGive.setSelected(norMarListBean.isSupported() == CommentBean.TRUE);
                        mIvCommentGive.setLiked(norMarListBean.isSupported() == CommentBean.TRUE);
                    }
                }

                @Override
                public void onGiveFail() {
                    //ToastUtils.showShort(getContext(), "网络错误");
                }
            });
        }
    }

    /**
     * 主评论点赞
     *
     * @param mTvCommentGiveNum
     * @param listener
     */
    public void giveClick(CommentBean.DataBean.CommentInfoBean.ReplyCommentsBean replyCommentsBean, TextView mTvCommentGiveNum, LikeButton ivCommentGive, OnGiveFinishListener listener) {
        String giveNum = mTvCommentGiveNum.getText().toString().trim();

        if (TextUtils.isEmpty(giveNum))
            return;

        if (!ivCommentGive.isLiked()) {
            //取消点赞
            favoriteFun(activity, SpUtils.getInstance().getLoadUserBean().getData().getToken(), "1", String.valueOf(replyCommentsBean.getId()), false, new OnGiveListener() {
                @Override
                public void onGiveSuccess() {
                    int giveI = Integer.parseInt(giveNum);
                    if (giveI > 0) {
                        giveI = giveI - 1;
                    } else {
                        giveI = 0;
                    }

                    if (listener != null) {
                        listener.onGiveFinish();
                        replyCommentsBean.setSupported(CommentBean.FALSE);
                        replyCommentsBean.setSupportNum(giveI);
                        mTvCommentGiveNum.setText(String.valueOf(replyCommentsBean.getSupportNum()));
                        mTvCommentGiveNum.setVisibility(replyCommentsBean.getSupportNum() == 0 ? INVISIBLE : VISIBLE);
                        ivCommentGive.setLiked(replyCommentsBean.isSupported() == CommentBean.TRUE);
                    }
                }

                @Override
                public void onGiveFail() {
                    //ToastUtils.showShort(getContext(), "网络错误");
                }
            });
        } else {
            //点赞
            favoriteFun(activity, SpUtils.getInstance().getLoadUserBean().getData().getToken(), "1", String.valueOf(replyCommentsBean.getId()), true, new OnGiveListener() {
                @Override
                public void onGiveSuccess() {
                    int giveI = Integer.parseInt(giveNum);
                    giveI++;
                    if (listener != null) {
                        listener.onGiveFinish();
                        replyCommentsBean.setSupported(CommentBean.TRUE);
                        replyCommentsBean.setSupportNum(giveI);
                        mTvCommentGiveNum.setText(String.valueOf(replyCommentsBean.getSupportNum()));
                        mTvCommentGiveNum.setVisibility(replyCommentsBean.getSupportNum() == 0 ? INVISIBLE : VISIBLE);
                        ivCommentGive.setLiked(replyCommentsBean.isSupported() == CommentBean.TRUE);
                    }
                }

                @Override
                public void onGiveFail() {
                    //ToastUtils.showShort(getContext(), "网络错误");
                }
            });
        }
    }


    /**
     * @param type
     * @param typeId 评论ID
     * @param flag   true 点赞 false 取消点赞
     */
    public static void favoriteFun(Activity activity, String token, String type, String typeId, boolean flag, OnGiveListener listener) {
        if (listener == null)
            return;
        ScreenUtils.sendPhoneShock(activity, 50);
        // LoadingManager.showLoadingDialog(activity);
        if (flag) {
            SendRequest.web_support_add(token, type, typeId, new GenericsCallback<String>(new JsonGenericsSerializator()) {

                @Override
                public void onError(Call call, Exception e, int id) {
                    //LoadingManager.hideLoadingDialog(activity);
                    listener.onGiveFail();
                }

                @Override
                public void onResponse(String response, int id) {
                    //  LoadingManager.hideLoadingDialog(activity);
                    try {
                        JSONObject mJsonObject = new JSONObject(response);
                        boolean aBoolean = mJsonObject.getBoolean("success");
                        if (aBoolean) {
                            listener.onGiveSuccess();
                        } else {
                            listener.onGiveFail();
                        }
                    } catch (JSONException e) {
                        listener.onGiveFail();
                        e.printStackTrace();
                    }
                }
            });
        } else {
            SendRequest.web_support_delete(token, type, typeId, new GenericsCallback<String>(new JsonGenericsSerializator()) {

                @Override
                public void onError(Call call, Exception e, int id) {
                    LoadingManager.hideLoadingDialog(activity);
                    listener.onGiveFail();
                }

                @Override
                public void onResponse(String response, int id) {
                    LoadingManager.hideLoadingDialog(activity);

                    try {
                        JSONObject mJsonObject = new JSONObject(response);
                        boolean aBoolean = mJsonObject.getBoolean("success");
                        if (aBoolean) {
                            listener.onGiveSuccess();
                        } else {
                            listener.onGiveFail();
                        }
                    } catch (JSONException e) {
                        listener.onGiveFail();
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * @param textView
     * @param imageView
     * @return
     */
    public static int calculationGiveNum(TextView textView, ImageView imageView) {

        String giveNum = textView.getText().toString().trim();
        int giveI = 0;
        if (TextUtils.isEmpty(giveNum)) {
            giveNum = "0";
        }
        try {
            giveI = Integer.parseInt(giveNum);
        } catch (NumberFormatException e) {
            e.getMessage();
        }

        if (imageView.isSelected()) {
            //取消点赞
            if (giveI > 0) {
                giveI--;
            } else {
                giveI = 0;
            }
        } else {
            giveI++;
        }
        return giveI;
    }


    public static void webCommentDel(Activity activity, int commentId, OnDeleteCommentListener listener) {
        if (listener == null)
            return;

        DialogManager.showConfirmDialog(activity, "确认要删除评论吗？", new DialogManager.Listener() {
            @Override
            public void onItemLeft() {

            }

            @Override
            public void onItemRight() {
                SendRequest.web_comment_del(SpUtils.getInstance().getLoadUserBean().getData().getToken(), commentId,
                        new GenericsCallback<BaseData>(new JsonGenericsSerializator()) {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                listener.onFail();
                            }

                            @Override
                            public void onResponse(BaseData response, int id) {
                                if (response.isSuccess())
                                    listener.onSuccess();
                                else
                                    listener.onFail();
                            }
                        });
            }
        });
    }

    /**
     * 举报
     *
     * @param id
     * @param userId
     */
    public static void reportComment(Activity activity, int id, int userId) {
        Bundle bundle = new Bundle();
        bundle.putInt("type", 2);
        bundle.putInt("id", id);
        bundle.putInt("complaintUserId", userId);
        Intent intent = new Intent(activity, mCommentHelp.getJuBaoOneActivity());
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    /**
     * 创建子评论实体类
     *
     * @param newChildrenCommentData
     * @return
     */
    @NotNull
    public static CommentBean.DataBean.CommentInfoBean.ReplyCommentsBean createReplyCommentsBean(CommentReplyBean.DataBean newChildrenCommentData) {
        CommentBean.DataBean.CommentInfoBean.ReplyCommentsBean replyCommentsBean = new CommentBean.DataBean.CommentInfoBean.ReplyCommentsBean();
        replyCommentsBean.setCommentNum(newChildrenCommentData.getCommentNum());
        replyCommentsBean.setContent(newChildrenCommentData.getContent());
        replyCommentsBean.setId(newChildrenCommentData.getId());
        replyCommentsBean.setCtime(newChildrenCommentData.getCtime());
        replyCommentsBean.setCueCid(newChildrenCommentData.getCueCid());
        replyCommentsBean.setCueContent(newChildrenCommentData.getCueContent());
        replyCommentsBean.setPid(newChildrenCommentData.getPid());
        replyCommentsBean.setPuid(newChildrenCommentData.getPuid());
        replyCommentsBean.setPuname(newChildrenCommentData.getPuname());
        replyCommentsBean.setType(newChildrenCommentData.getType());
        replyCommentsBean.setTypeId(newChildrenCommentData.getTypeId());
        replyCommentsBean.setReplyContent(newChildrenCommentData.getReplyContent());
        replyCommentsBean.setSupported(newChildrenCommentData.isSupported());
        replyCommentsBean.setStatus(newChildrenCommentData.getStatus());
        replyCommentsBean.setUser(newChildrenCommentData.getUser());
        replyCommentsBean.setReplyComments(newChildrenCommentData.getReplyComments());
        return replyCommentsBean;
    }

    /**
     * 评论详情界面---创建子评论实体类
     *
     * @param newChildrenCommentData
     * @return
     */
    @NotNull
    public static CommentBean.DataBean.CommentInfoBean.ReplyCommentsBean createDetailsReplyCommentsBean(CommentBean.DataBean.CommentInfoBean newChildrenCommentData) {
        CommentBean.DataBean.CommentInfoBean.ReplyCommentsBean replyCommentsBean = new CommentBean.DataBean.CommentInfoBean.ReplyCommentsBean();
        replyCommentsBean.setCommentNum(newChildrenCommentData.getCommentNum());
        replyCommentsBean.setContent(newChildrenCommentData.getContent());
        replyCommentsBean.setId(newChildrenCommentData.getId());
        replyCommentsBean.setCtime(newChildrenCommentData.getCtime());
        replyCommentsBean.setCueCid(newChildrenCommentData.getCueCid());
        replyCommentsBean.setCueContent(newChildrenCommentData.getCueContent());
        replyCommentsBean.setPid(newChildrenCommentData.getPid());
        replyCommentsBean.setPuid(newChildrenCommentData.getPuid());
        replyCommentsBean.setPuname(newChildrenCommentData.getPuname());
        replyCommentsBean.setType(newChildrenCommentData.getType());
        replyCommentsBean.setTypeId(newChildrenCommentData.getTypeId());
        replyCommentsBean.setReplyContent(newChildrenCommentData.getReplyContent());
        replyCommentsBean.setSupported(newChildrenCommentData.isSupported());
        replyCommentsBean.setStatus(newChildrenCommentData.getStatus());
        replyCommentsBean.setUser(newChildrenCommentData.getUser());
        replyCommentsBean.setReplyComments(newChildrenCommentData.getReplyComments());
        return replyCommentsBean;
    }


    public static void openCommentPanel(Activity activity, int type, int typeId, int pId, int puId, Serializable o) {
        Intent intent = new Intent(activity, mCommentHelp.getWindowAddComment());
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        bundle.putBoolean("isShowReply", true);
        bundle.putInt("typeId", typeId);
        bundle.putInt("pId", pId);
        bundle.putInt("puId", puId);
        bundle.putSerializable("dataBean", o);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }


    public static void openCommentActivity(Activity activity, int type, int videoId, String exisContent, String name, boolean isShowReply, int code) {
        Bundle bundle = new Bundle();
        //type:评论类型 1评论的评论 4文章评论 5产品评论 6动态评论 7专栏评论 8话题评论 9话题动态评论 10 讲坛评论 11 课程评论
        bundle.putInt("type", type);
        bundle.putInt("typeId", videoId);
        bundle.putString("content", (exisContent.equals(CommentConstant.COMMENT_DEF_CONTENT_VERSION_1_COPY)
                || exisContent.equals(CommentConstant.COMMENT_DEF_CONTENT_VERSION_1)
                || exisContent.equals(CommentConstant.COMMENT_DEF_CONTENT_VERSION_2)) ? "" : exisContent);
        bundle.putBoolean("isShowReply", isShowReply);
        bundle.putSerializable("title", name);
        Intent mIntent = new Intent(activity, mCommentHelp.getWindowAddComment());
        mIntent.putExtras(bundle);
        activity.startActivityForResult(mIntent, code); //此处的requestCode应与下面结果处理函中调用的requestCode一致

    }


    public static void openUserInfo(Activity activity, int userId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put(BaseConstant.USER_ID, String.valueOf(userId));
        ARouterUtils.jump(ActivityRouter.MINE_CENTER.USER_INFO, hashMap);
    }



    public void setSayContent(int requestCode, int resultCode, @Nullable Intent data, TextView textView, String defContent) {
        if (requestCode == CommentConstant.COMMENT_REQUESTCODE && resultCode == CommentConstant.COMMENT_RESPONSE) {
            if (data != null) {
                if (!TextUtils.isEmpty(data.getStringExtra(CommentConstant.COMMENT_CONTENT))) {
                    textView.setText(data.getStringExtra(CommentConstant.COMMENT_CONTENT));
                } else {
                    textView.setText(defContent);
                }
            }
        }
    }

    public int upCommentNum(int requestCode, int resultCode, @Nullable Intent data, int oldNum, TextView textView) {
        if (requestCode == CommentConstant.COMMENT_REQUESTCODE && resultCode == CommentConstant.COMMENT_RESPONSE) {
            if (data != null) {
                if (data.hasExtra(CommentConstant.COMMENT_IS_VIOLATION)) {
                    boolean isShowReply = data.getBooleanExtra(CommentConstant.COMMENT_IS_VIOLATION, false);// false = 一级评论
                    if (!isShowReply) {
                        oldNum++;
                        textView.setText(String.valueOf(oldNum));
                        textView.setVisibility(VISIBLE);
                    }
                }
            }
            return oldNum;
        }
        return -1;
    }

    public int upCommentNum(int requestCode, int resultCode, @Nullable Intent data, int oldNum) {
        if (requestCode == CommentConstant.COMMENT_REQUESTCODE && resultCode == CommentConstant.COMMENT_RESPONSE) {
            if (data != null) {
                if (data.hasExtra(CommentConstant.COMMENT_IS_VIOLATION)) {
                    boolean isShowReply = data.getBooleanExtra(CommentConstant.COMMENT_IS_VIOLATION, false);// false = 一级评论
                    if (!isShowReply) {
                        oldNum++;
                    }
                }
            }
            return oldNum;
        }
        return -1;
    }

    /**
     * @param tagView
     * @des 从不亮到高亮。。从高亮到不亮
     */
    public static void setCommentProminent(View tagView) {
        AlphaAnimation alphaAnim = new AlphaAnimation(0, 1f);
        alphaAnim.setDuration(1500);
        alphaAnim.setFillAfter(true);
        tagView.startAnimation(alphaAnim);

        alphaAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                tagView.postDelayed(() -> {
                    AlphaAnimation alphaAnim1 = new AlphaAnimation(1f, 0);
                    alphaAnim1.setDuration(1000);
                    alphaAnim1.setFillAfter(true);
                    tagView.startAnimation(alphaAnim1);
                    tagView.setVisibility(GONE);
                }, 500);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }


    public interface OnGiveListener {
        void onGiveSuccess();

        void onGiveFail();
    }


    public interface OnGiveFinishListener {
        void onGiveFinish();
    }

    public interface OnDeleteCommentListener {
        void onSuccess();

        void onFail();
    }

    public interface OnEndingViewListener {
        void onEndingListener();
    }

}
